import React, { useState, useMemo, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Search, Copy, ChevronDown, ChevronRight, Download, Wand2, Check, AlertTriangle } from "lucide-react";
import { SystemVariableConfig } from "@/api/entities";

const VariableItem = ({ variable, onInsert, isStandalone }) => {
  const [copiedKey, setCopiedKey] = useState(false);

  const handleCopy = (text) => {
    navigator.clipboard.writeText(text);
    setCopiedKey(true);
    setTimeout(() => setCopiedKey(false), 1500);
  };

  const handleClick = () => {
    const varText = `{{${variable.variable_key}}}`;
    if (isStandalone) {
      handleCopy(varText);
    } else {
      onInsert(varText);
    }
  };

  return (
    <div className={`group p-3 border rounded-lg hover:bg-gray-50 transition-colors ${variable.is_deprecated ? 'bg-red-50 border-red-200' : ''}`}>
      <div className="flex items-start justify-between">
        <div className="flex-1 min-w-0">
          <div 
            className="font-mono text-sm text-blue-600 mb-1 flex items-center gap-2 cursor-pointer" 
            title={isStandalone ? "点击复制" : "点击插入"}
            onClick={handleClick}
          >
            <span className="break-all">{`{{${variable.variable_key}}}`}</span>
            {isStandalone ? 
              (copiedKey ? <Check className="w-4 h-4 text-green-600 flex-shrink-0" /> : <Copy className="w-4 h-4 text-gray-400 group-hover:text-blue-600 flex-shrink-0" />) :
              <Wand2 className="w-4 h-4 text-gray-400 group-hover:text-blue-600 flex-shrink-0" title="点击插入" />
            }
          </div>
          <p className="text-xs text-gray-600 mb-2 break-words">{variable.description}</p>
          
          {variable.is_deprecated && (
            <div className="text-xs text-red-600 flex items-center gap-1 mb-2">
                <AlertTriangle className="w-4 h-4" />
                <span>此变量已弃用，源字段可能已不存在。</span>
            </div>
          )}

          <div className="text-xs text-gray-500 italic bg-gray-50 p-2 rounded-md border">
            <span className="font-semibold not-italic">示例:</span>
            <pre className="whitespace-pre-wrap word-wrap break-words font-sans mt-1 text-xs leading-relaxed overflow-hidden">
              {variable.example}
            </pre>
          </div>
        </div>
      </div>
    </div>
  );
};

const VariableCategory = ({ categoryName, categoryData, isOpen, onToggle, onInsert, isStandalone }) => (
  <Collapsible open={isOpen} onOpenChange={onToggle}>
    <CollapsibleTrigger asChild>
      <Button variant="ghost" className="w-full justify-between p-3 h-auto hover:bg-blue-50">
        <div className="flex items-center gap-3 text-left">
          <span className="text-xl">{categoryData.icon}</span>
          <div>
            <div className="font-semibold text-gray-800">{categoryName}</div>
            <p className="text-xs text-gray-500 font-normal">{categoryData.description}</p>
          </div>
        </div>
        {isOpen ? <ChevronDown className="w-5 h-5" /> : <ChevronRight className="w-5 h-5" />}
      </Button>
    </CollapsibleTrigger>
    <CollapsibleContent className="space-y-2 p-2 pt-0">
      {categoryData.variables.map((variable) => (
        <VariableItem 
          key={variable.id} 
          variable={variable} 
          onInsert={onInsert}
          isStandalone={isStandalone}
        />
      ))}
    </CollapsibleContent>
  </Collapsible>
);

export default function VariableReferenceGuide({ onInsertVariable }) {
  const [searchTerm, setSearchTerm] = useState("");
  const [allVariables, setAllVariables] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [expandedCategories, setExpandedCategories] = useState({});

  const isStandalone = !onInsertVariable;

  useEffect(() => {
    const loadData = async () => {
      setIsLoading(true);
      try {
        const data = await SystemVariableConfig.list('-created_date');
        setAllVariables(data || []);
        // Default expand the first category
        if (data && data.length > 0) {
            const firstCategory = data[0].category;
            setExpandedCategories({ [firstCategory]: true });
        }
      } catch (error) {
        console.error("Failed to load system variables:", error);
      } finally {
        setIsLoading(false);
      }
    };
    loadData();
  }, []);
  
  const toggleCategory = (category) => {
    setExpandedCategories(prev => ({ ...prev, [category]: !prev[category] }));
  };

  const groupedAndFilteredVariables = useMemo(() => {
    const lowercasedFilter = searchTerm.toLowerCase();
    
    const filtered = searchTerm
      ? allVariables.filter(v =>
          v.variable_key.toLowerCase().includes(lowercasedFilter) ||
          v.description.toLowerCase().includes(lowercasedFilter) ||
          v.category.toLowerCase().includes(lowercasedFilter)
        )
      : allVariables;

    const grouped = filtered.reduce((acc, v) => {
      const category = v.category || "未分类";
      if (!acc[category]) {
        acc[category] = {
          icon: v.category_icon || '❓',
          description: `${category}相关的变量`,
          variables: []
        };
      }
      acc[category].variables.push(v);
      return acc;
    }, {});
    
    return grouped;
  }, [searchTerm, allVariables]);

  const downloadGuide = () => {
    let content = "# 文档模板变量使用指南\n\n";
    for (const category in groupedAndFilteredVariables) {
      content += `## ${groupedAndFilteredVariables[category].icon} ${category}\n\n`;
      content += `| 变量 | 描述 | 状态 |\n`;
      content += `| :--- | :--- | :--- |\n`;
      groupedAndFilteredVariables[category].variables.forEach(v => {
        content += `| \`{{${v.variable_key}}}\` | ${v.description} | ${v.is_deprecated ? '已弃用' : '活跃'} |\n`;
      });
      content += `\n`;
    }

    const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '变量使用指南.md';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  return (
    <div className="h-full flex flex-col">
      <div className="flex-shrink-0 mb-3 p-4 border-b">
        <div className="flex items-center justify-between mb-2">
          <h3 className="text-base font-semibold">变量参考手册</h3>
          <Button variant="ghost" size="sm" onClick={downloadGuide} className="text-xs">
            <Download className="w-3 h-3 mr-1" />
            MD指南
          </Button>
        </div>
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-4 h-4" />
          <Input
            placeholder="搜索变量..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10 h-9"
          />
        </div>
      </div>
      
      <div className="flex-1 overflow-y-auto overflow-x-hidden p-2">
        {isLoading ? (
            <div className="text-center p-6 text-gray-500">加载中...</div>
        ) : Object.keys(groupedAndFilteredVariables).length > 0 ? (
          Object.entries(groupedAndFilteredVariables).map(([categoryName, categoryData]) => (
            <VariableCategory
              key={categoryName}
              categoryName={categoryName}
              categoryData={categoryData}
              isOpen={searchTerm ? true : !!expandedCategories[categoryName]}
              onToggle={() => toggleCategory(categoryName)}
              onInsert={onInsertVariable}
              isStandalone={isStandalone}
            />
          ))
        ) : (
          <div className="text-center p-6 text-gray-500">
            <p>未找到匹配的变量</p>
          </div>
        )}
      </div>
    </div>
  );
}